$(function () {
    $('#goLogin').on('click', function () {
        $('.login-box').stop().show();
        $('.registry-box').stop().hide();
    })
    $('#goRegistry').on('click', function () {
        $('.login-box').stop().hide();
        $('.registry-box').stop().show();
    })

    let form = layui.form;
    let layer = layui.layer;
    form.verify({
        username: function (value, item) { //value：表单的值、item：表单的DOM对象
            if (!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)) {
                return '用户名不能有特殊字符';
            }
            if (/(^\_)|(\__)|(\_+$)/.test(value)) {
                return '用户名首尾不能出现下划线\'_\'';
            }
            if (/^\d+\d+\d$/.test(value)) {
                return '用户名不能全为数字';
            }
        }

        //我们既支持上述函数式的方式，也支持下述数组的形式
        //数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]
        , pass: [
            /^[\S]{6,12}$/
            , '密码必须6到12位，且不能出现空格'
        ],
        repass: function (value) {
            if (value != $('.registry-box [name=password]').val()) {
                return '输入密码不一致'
            }
        }
    });

    //登录
    $('#login-form').on('submit', function (e) {
        e.preventDefault()
        let username = $('#login-form [name=username]').val();
        let password = $('#login-form [name=password]').val();
        $.ajax({
            method:'post',
            url:'/api/login',
            data:{
                username,
                password
            },
            success(res){
                if (res.status === 0) {
                    localStorage.setItem('BigDashijianToken' , res.token)
                    location.href ='index.html'
                } else {
                    layer.msg(res.message, { icon: 2 })
                }
            }
        })
    });



    $('#registry-form').on('submit', function (e) {
        e.preventDefault()
        let username = $('#registry-form [name=username]').val();
        let password = $('#registry-form [name=password]').val();
        $.ajax({
            method: 'post',
            url: '/api/reguser',
            data: {
                username,
                password
            },
            success: function (res) {
                if (res.status === 0) {
                    localStorage.setItem('BigDashijianToken' , res.token)
                    $('#goLogin').click();

                } else {
                    layer.msg(res.message, { icon: 2 })
                }
            }
        })
    });

})